package leetcode

import kotlinetc.println

/**
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

1     2      3       4

12    13      14      5

11    16      15      6

10    9       8       7
 */

fun main(args: Array<String>) {

    generateMatrix(4).asList().forEach {
        it.asList().println()
    }

}

var number = 0
fun generateMatrix(n: Int): Array<IntArray> {

    val result = Array(n) { IntArray(n) { 0 } }

    val cycleTime = (n + 1) / 2

    var l = 0
    var r = n - 1
    var t = 0
    var b = n - 1
    for (i in 0 until cycleTime) {

        val arr = result[t]
        var j = l
        while (j <= r) {
            arr[j] = next()
            j++
        }
        j--

        var k = t + 1
        while (k <= b && l < r) {
            result[k][j] = next()
            k++
        }

        k = r - 1
        while (k >= l && t < b) {
            result[b][k] = next()
            k--
        }

        k = b - 1
        while (k > t) {
            result[k][l] = next()
            k--
        }

        l++
        r--
        t++
        b--
    }

    return result

}

fun next(): Int {
    return ++number
}